#include <iostream>
using namespace std;

const int N = 50010;
int p[N], rela[N];
int n, k, D, X, Y, mis;

void init(int n)
{
    mis = 0;
    for (int i = 1; i <= n; ++i)
    {
        p[i] = i;
    }
    return;
}

int find(int x)
{
    if (p[x] != x)
    {
        int u = find(p[x]);
        rela[x] += rela[p[x]];
        p[x] = u;
    }
    rela[x] %= 3;
    return p[x];
}

void merge(int D, int X, int Y)
{
    int px = find(X), py = find(Y);
    p[px] = py;
    rela[px] = (3 - rela[X] + D - 1 + rela[Y]) % 3;
    return;
}

int query(int D, int X, int Y)
{
    if (X > n || Y > n)
        return -1;
    else if (find(X) != find(Y))
        return 0;
    else if ((rela[X] + 3 - rela[Y]) % 3 != D - 1)
        return -1;
    else
        return 1;
}

int main()
{
    cin >> n >> k;
    init(n);
    while (k--)
    {
        cin >> D >> X >> Y;
        if (query(D, X, Y) == 0)
            merge(D, X, Y);
        else if (query(D, X, Y) == -1)
            ++mis;
    }
    cout << mis;
    return 0;
}